package game.leon.engine.script;

import java.io.UnsupportedEncodingException;

/**
 * 字符串的数据源, 还有一个就是来自文件的数据源, 实际上是一样的
 * User: bianpeng
 * Date: 12-2-3
 */
public class StringSource implements Source {
    private byte[] script;
    private int offset;  // 偏移量
    private int bufsize;
    public StringSource(byte[] script, int bufsize) {
        this.script = script;
        this.bufsize = bufsize;
        offset = 0;
    }

    public StringSource(String script, int bufsize) {
        try {
            this.script = script.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        this.bufsize = bufsize;
        offset = 0;
    }

    @Override
    public int fillBuffer(Buffer buffer) {
        int n = Math.min(script.length - offset, bufsize >> 1);
        buffer.fill(script, offset, n);
        offset += n;
        return n;
    }
    @Override
    public boolean eof() {
        return offset >= script.length;
    }

    @Override
    public int bufsize() {
        return this.bufsize;
    }
}
